#!/usr/bin/python
#
# This module uses the Google Data API's Python client library
# to interface with the Blogger service.  
# There are methods for the following operations:
#
# * Retrieving the list of all the user's blogs
# * Retrieving all posts on a single blog
# * Performing a date-range query for posts on a blog
# * Creating draft posts and publishing posts
# * Updating posts
# * Retrieving comments
# * Creating comments
# * Deleting comments
# * Deleting posts


__author__ = 'firstinfobot at gmail dot com'


from gdata import service
import gdata
import atom
import getopt
import sys

##############################################################################
class Blogger(object):

  def __init__(self, email, password, source, blog_index = 0):
    """Creates a GDataService and provides ClientLogin auth details to it.
          email and password are required arguments for ClientLogin.  
          source defined below is an arbitrary string, but should be used to
                 reference your name or the name of your organization, 
                 the app name and version, 
                 with '-' between each of the three values.
    """

    # Authenticate using ClientLogin.
    self.service = service.GDataService(email, password)
    self.service.source = source
    self.service.service = 'blogger'
    self.service.server = 'www.blogger.com'
    self.service.ProgrammaticLogin()

    
    # Get the blog ID for the blog_index blog
    feed = self.service.Get('/feeds/default/blogs')
    self_link = feed.entry[blog_index].GetSelfLink()
    if self_link:
      self.blog_id = self_link.href.split('/')[-1]

  def CreatePost(self, title, content, author_name, is_draft):
    """This method creates a new post on a blog.  The new post can be stored as
    a draft or published based on the value of the is_draft parameter.  The
    method creates an GDataEntry for the new post using the title, content,
    author_name and is_draft parameters.  With is_draft, True saves the post as
    a draft, while False publishes the post.  Then it uses the given
    GDataService to insert the new post.  If the insertion is successful, the
    added post (GDataEntry) will be returned.
    """

    # Create the entry to insert.
    entry = gdata.GDataEntry()
    entry.author.append(atom.Author(atom.Name(text=author_name)))
    entry.title = atom.Title(title_type='xhtml', text=title)
    entry.content = atom.Content(content_type='html', text=content)
    if is_draft:
      control = atom.Control()
      control.draft = atom.Draft(text='yes')
      entry.control = control

    # Ask the service to insert the new entry.
    return self.service.Post(entry, 
      '/feeds/' + self.blog_id + '/posts/default')

  def GetPosts(self, target):
    """This method gets all the posts in a blog."""

    # Request the feed.
    feed = self.service.GetFeed('/feeds/' + self.blog_id + '/posts/default')

    # Process the feed.
    target.add_feed_title(feed.title.text)
    for entry in feed.entry:
      target.add_entry_title(entry.title.text)
    

  def GetPostsInDateRange(self, target, start_time, end_time):
    """This method displays the title and modification time for any posts that
    have been created or updated in the period between the start_time and
    end_time parameters.  The method creates the query, submits it to the
    GDataService, and then displays the results.
  
    Note that while the start_time is inclusive, the end_time is exclusive, so
    specifying an end_time of '2007-07-01' will include those posts up until
    2007-6-30 11:59:59PM.

    The start_time specifies the beginning of the search period (inclusive),
    while end_time specifies the end of the search period (exclusive).
    """

    # Create query and submit a request.
    query = service.Query()
    query.feed = '/feeds/' + self.blog_id + '/posts/default'
    query.updated_min = start_time
    query.updated_max = end_time
    query.orderby = 'updated'
    feed = self.service.Get(query.ToUri())

    # Process the feed.
    target.add_feed_title(feed.title.text)
    target.add_date_range(start_time, end_time)
    for entry in feed.entry:
      target.add_entry_title(entry.title.text)
      target.add_entry_content(entry.title.content)

  def UpdatePostTitle(self, entry_to_update, new_title):
    """This method updates the title of the given post.  The GDataEntry object
    is updated with the new title, then a request is sent to the GDataService.
    If the insertion is successful, the updated post will be returned.

    Note that other characteristics of the post can also be modified by
    updating the values of the entry object before submitting the request.

    The entry_to_update is a GDatEntry containing the post to update.
    The new_title is the text to use for the post's new title.  Returns: a
    GDataEntry containing the newly-updated post.
    """
    
    # Set the new title in the Entry object
    entry_to_update.title = atom.Title('xhtml', new_title)
    
    # Grab the edit URI
    edit_uri = entry_to_update.GetEditLink().href  

    return self.service.Put(entry_to_update, edit_uri)

  def CreateComment(self, post_id, comment_text):
    """This method adds a comment to the specified post.  First the comment
    feed's URI is built using the given post ID.  Then a GDataEntry is created
    for the comment and submitted to the GDataService.  The post_id is the ID
    of the post on which to post comments.  The comment_text is the text of the
    comment to store.  Returns: an entry containing the newly-created comment

    NOTE: This functionality is not officially supported yet.
    """

    # Build the comment feed URI
    feed_uri = '/feeds/' + self.blog_id + '/' + post_id + '/comments/default'

    # Create a new entry for the comment and submit it to the GDataService
    entry = gdata.GDataEntry()
    entry.content = atom.Content(content_type='xhtml', text=comment_text)
    return self.service.Post(entry, feed_uri)

  def GetAllComments(self, post_id):
    """This method displays all the comments for the given post.  First the
    comment feed's URI is built using the given post ID.  Then the method
    requests the comments feed and displays the results.  Takes the post_id
    of the post on which to view comments. 
    """

    # Build comment feed URI and request comments on the specified post
    feed_url = '/feeds/' + self.blog_id + '/comments/default'
    feed = self.service.Get(feed_url)

    # Process the feed.
    target.add_feed_title(feed.title.text)
    for entry in feed.entry:
      target.add_entry_title(entry.title.text)
      target.add_entry_update(entry.updated.text)

  def DeleteComment(self, post_id, comment_id):
    """This method removes the comment specified by the given edit_link_href, the
    URI for editing the comment.
    """
    
    feed_uri = '/feeds/' + self.blog_id + '/' + post_id + '/comments/default/' + comment_id
    self.service.Delete(feed_uri)

  def DeletePost(self, edit_link_href):
    """This method removes the post specified by the given edit_link_href, the
    URI for editing the post.
    """
    self.service.Delete(edit_link_href)
  

